package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.feign.CacheService;
import com.qf.model.StandardSubmit;
import com.qf.service.StrategyService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 扣费策略
 * @author lenovo
 * @version V1.0
 * @Date 2021/11/22 21:37
 */
@Component(value = "fee")
@Slf4j
public class FeeFilterServiceImpl implements StrategyService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public Boolean execute(StandardSubmit standardSubmit) {
        log.info("【策略模块 - 扣费策略】开始执行，短信对象内容 standardSubmit={}",standardSubmit);
        //1.获取当前客户的充值余额
        Map<String,String> client = cacheService.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID());
        Long totalFee = Long.parseLong(client.get("fee"));
        //2.获取当前短信的这一条费用
        Long fee = standardSubmit.getFee();

        //3.判断用户的余额是否够用
        if (totalFee >= fee){
            //4.扣减费用计算 = 用户余额 - 当前短信需要的费用
            cacheService.hincr(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(), "fee", -fee);
            log.info("【策略模块 - 扣费策略】扣费成功，短信对象内容 standardSubmit={}",standardSubmit);
            return true;
        }

        //5.如果扣费失败，发送report返回的消息对象到mq的队列中，通知用户项目扣费失败的原因
        log.info("【策略模块 - 扣费策略】扣费失败，用户余额不足");
        pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
        pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
        return false;
    }
}
